'use strict';
var  fs = require('fs');
var _ = require('underscore');
var path = require('path');
var mkdirp = require('mkdirp');
var cache = require('./patient_cache');
var utils = require('./utils');

var NUMBER_OF_RESULTS = 50;

//////////////////////////// PATIENTS

var generateIndexForPatientListFromInputRequest = function (req) 
{
	console.log(" generateIndexForPatientListFromInputRequest  ");
	var patientnom;
	var patientprenom;
	var patientid;
	if (req && req.params) {
		if (req.body && req.body.path) {
			console.log("body = " + JSON.stringify(req.body));
			return req.body;
		}
		else {
			if (req.params.name) {
				console.log(" nom = " + req.params.name);
				patientnom = req.params.name;
				patientnom = patientnom.substr(1,patientnom.length);
			}
			if (req.params.surname) {
				console.log(" prenom = " + req.params.surname);
				patientprenom = req.params.surname;
				patientprenom = patientprenom.substr(1,patientprenom.length);
			}
			if (req.params.id) {
				console.log(" id = " + req.params.id);
				patientid = req.params.id;
				patientid = patientid.substring(1,patientid.length);
			}	
		}
	}

	var patientIndex = cache.getJsonIndexForPatient(patientnom, patientprenom, patientid);
	if (patientIndex.generated && (patientIndex.nom || patientIndex.prenom)) 
		patientIndex = utils.parseFileNameToGetJsonIndex({Path:cache.resolveFileNameForMedecin(patientIndex), IsDirectory : false});
	return patientIndex;
}

// GET

exports.getAllPatients = function(req,res) {

	console.log("\n\n DEBUG-api: getAllPatients ")

	var patientIndex = generateIndexForPatientListFromInputRequest(req);

	console.log("NOMS : " + patientIndex.noms);
	
	try {
	
		if (cache.data.patients.length > 0) {
		
			var filteredList = cache.data.patients;
			console.log("NOMS : " + patientIndex.noms);
			if (patientIndex.noms) {
				patientIndex.noms.forEach(function(nom) {
					filteredList  = _.filter(cache.data.patients, function(patient){ 
						return (patient.path.toLowerCase().indexOf(nom.toLowerCase())>0); 
					});
				});
			}
			if(res) res.json(filteredList.slice(0,NUMBER_OF_RESULTS));
			return;
		}
	
		var files = utils.browseAllPatientFolders(utils.PATIENTS_FOLDER);
		
		//console.log("files "+files);
		
		files.forEach(function(file)
		{
			var json = utils.parseFileNameToGetJsonIndex(file);
			if (json != null) cache.data.patients.push(json);
		});
		
		if(res) res.json(cache.data.patients.slice(0,NUMBER_OF_RESULTS));
		console.log("getAllPatients - SENT: #" + cache.data.patients.length+ " patients");
//		console.log("getAllPatients - SENT: "+JSON.stringify(cache.data.patients,null,3));
	}
	catch (err) {
		console.log("Error occurred while reading file "+err);
		if(res) res.send(404);
	}
}


/* *
 * Mehtode pour la lecture des patients dans le file system
 * @params: /:name/:surname/:id
 */
exports.getPatient = function(req,res) {

console.log("\n\n DEBUG-api: getPatient ")


	var patientIndex = generateIndexForPatientListFromInputRequest(req);
	
	try {
	
		var filename = patientIndex.path;
		console.log("DEBUG-api: Filename generated: " + JSON.stringify(patientIndex));
		fs.readFile(filename,{encoding:'utf8'}, function(err,patientString) {
			if(err) {
				console.log(err);
				res.send(404);
			} else {
				console.log("The file was read!");
				patientString = patientString.toString('utf8').	replace(/^\uFEFF/, '').
																replace(/&gt/g,">").
																replace(/&lt/g,"<").
																replace(/"date": "([0-9]{4})([0-9]{2})([0-9]{2})"/g,"\"date\": \"$1-$2-$3\"").
																replace(/"date_naissance": "([0-9]{4})([0-9]{2})([0-9]{2})"/g,"\"date_naissance\": \"$1-$2-$3\"");
				
				var patientJson = JSON.parse(patientString);
				patientJson.consultations = _.sortBy(patientJson.consultations, function(f) { return f.date });
				patientJson.audiometries = _.sortBy(patientJson.audiometries, function(f) { return f.date });
				res.json(patientJson);
//				console.log("patientString = "+patientString);
			}
		});
	}
	catch (err) {
		console.log("Error occurred while reading file "+err);
		res.send(404);
	}
}


// POSTS
exports.updatePatient = function(req,res) {

console.log("\n\n DEBUG-api: updatePatient ")

	//console.log(req.body);
	try {
		var patientJson = req.body;
		var patientIndex = utils.getJsonIndexForPatient(patientJson.nom, patientJson.prenom, patientJson.id);
		
		var path = cache.resolveFileNameForMedecin(patientIndex);
		console.log("creating "+path);
		mkdirp(utils.resolveFolderName(utils.PATIENTS_FOLDER,patientJson.nom,patientJson.prenom),function(err){
//			res.send(404);
			if (err) {
				console.log("Error while creating folder" + err);
				res.send(404);
			}
			else {
				try {
				//var buffer = new Buffer(JSON.stringify(patientJson).toString('utf-8'),"utf-8");
					//if (patientid || patientid == -1) patientIndex = parseFileNameToGetJsonIndex({Name:resolveFileNameForMedecin(patientIndex), IsDirectory : false});
					console.log("DEBUG-api: Update Patient "+JSON.stringify(patientIndex));
					fs.writeFileSync(patientIndex.path, 
								JSON.stringify(patientJson).toString('utf-8'),
								//buffer.toString("utf-8"),
								'utf8');
				//buffer.write
				} catch(err) {
					console.log("Error occurred while saving file "+err);
					res.send(404);
					return;
				}
				console.log("The file was saved!");
				//_.sortedIndex(cache.data.patients,patientJson,'nom');
				//if (index >=0 && comparePatients(cache.data.patients[index],patientJson)) {
				var indexJson = cache.getIndexInPatientList(patientIndex);
				if (indexJson.match) {
//					cache.data.patients.splice(index,1,//getJsonIndexForPatient(patientJson));
//					parseFileNameToGetJsonIndex ());
					console.log(patientIndex.nom+": found at "+indexJson.index);
				}
				else {
					cache.data.patients.splice(indexJson.index+1,0,patientIndex);
					console.log(JSON.stringify(patientIndex)+": created");
				}
				//cache.data.patients = _.sortBy(cache.data.patients, function(f) { return f.nom });
				res.json(patientIndex);
			}
		});

	}
	catch (err) {
		console.log("Error occurred while saving file "+err);
		res.send(404);
	}
}

//DELETE
exports.deletePatient = function(req,res) {

	console.log("\n\n DEBUG-api: deletePatient ")

	console.log(req.body);
	
	var patientIndex = generateIndexForPatientListFromInputRequest(req);	

	try {

		// Ca plante ici
		var path = cache.resolveFileNameForMedecin(patientIndex);
		console.log("PATH = "+path);
		if (fs.existsSync(path)) {
			var indexInPatientList = cache.getIndexInPatientList(patientIndex);
			
			console.log(cache.data.patients[indexInPatientList.index].id + " =?= " + patientIndex.id);
			cache.data.patients.splice(indexInPatientList.index,1);
			fs.unlinkSync(path);
			res.send(200);
		}
		else {
			console.log(path+" cannot be removed");
			res.send(404);
		}
	}
	catch (err) {
		console.log("Error occurred while removing file "+err);
		res.send(404);
	}
}